package com.wngbms.redisson;

import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;

import java.io.InputStream;
import java.util.concurrent.TimeUnit;

/**
 * 延时Redisson主题订阅,消费
 */
@Slf4j
//@Component
public class RedissonTopic {

    @Bean
    public RedissonClient redissonClient() {
        return Redisson.create();
    }

    @Bean
    public ApplicationRunner applicationRunner(RedissonClient redissonClient) {
        return args -> {
            RTopic topic = redissonClient.getTopic("topic2");
            topic.addListener(String.class, (channel, msg) -> log.info("onMessage:{} {}", channel, msg));
            log.info("add success");
        };
    }

    @Bean
    public ApplicationRunner applicationRunner3(RedissonClient redissonClient) {
        return args -> {
            RTopic topic = redissonClient.getTopic("topic2");
            topic.addListener(String.class, (channel, msg) -> log.info("onMessage3:{} {}", channel, msg));
            log.info("add success3");
        };
    }

    @Bean
    public ApplicationRunner applicationRunner2(RedissonClient redissonClient) {
        return args -> {
            RTopic topic2 = redissonClient.getTopic("topic2");

            topic2.publish("sony headphone");
            log.info("publish success");
            TimeUnit.SECONDS.sleep(5);
            topic2.publish("apple headphone");
            log.info("publish success");

            log.info("请输入:");
            InputStream in = System.in;
            StringBuilder sb = new StringBuilder();
            while (true) {
                int ch = in.read();
                if (ch == '\r')
                    continue;
                if (ch == '\n') {
                    String s = sb.toString();
                    if ("over".equals(s))
                        break;
//                    System.out.println(s.toUpperCase());
                    String s1 = s.toUpperCase();
                    log.info("publish success:{}", s1);
                    topic2.publish(s1);
                    sb.delete(0, sb.length());
                } else
                    sb.append((char) ch);
            }
        };
    }

}
